<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Demo</title>
  <!-- 请勿在项目正式环境中引用该 layui.css 地址 -->
  <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
  <link rel="stylesheet" href="../css/public.css" media="all">
  <link rel="stylesheet" href="../js/lay-module/treetable-lay/treetable.css">
  <style>
    ::-webkit-scrollbar {  
	display: none;  
	}
    
    .input{
        width: 350px;
    }

    div#v_sp{
        background-image: url('');
        background-repeat: no-repeat; /* 背景图片不重复 */  
        background-position:-20px  -60px;
    }

    .inp{
        width: 200px;
        margin-top: 25px;
        margin-left: 10px;
    }
    

  </style>

</head>
<body>          
    
    <div class=" layui-form layuimini-container">
          <div class="layuimini-container" id="v_sp"  style="display: none;">

                <div class="layuimini-container " style=" margin-top:1px; margin-left: 620px;  " >
                  
                    <div class="layui-form-item inpspace">
                        <label class="layui-form-label required">编号</label>
                    <div class="layui-input-block">
                        <input  type="text"  id="vspecsId" name="vid" lay-verify="required" readonly  class="layui-input input inp">
                    </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label required">菜品名</label>
                        <div class="layui-input-block">
                            <input  type="text" name="vname"  lay-verify="required" readonly value="" class="layui-input input inp">
                        </div>
                    </div>  
                    

                    <div class="layui-form-item">
                        <label class="layui-form-label required">菜品价格</label>
                        <div class="layui-input-block">
                            <input  type="text" name="vprice" lay-verify="required" readonly value="" class="layui-input input inp">
                        </div>
                    </div>  


                    <div class="layui-form-item layui-form-text" style="margin-left:300px; position: absolute; top:80px;">
                        <label class="layui-form-label" style="margin-top:25px;">菜品描述</label>
                        <div class="layui-input-block">
                            <textarea name="vdepict" readonly class="layui-textarea" style="width: 250px;"></textarea>
                        </div>
                    </div>
                </div>                
        </div>


        <div class="layuimini-main">  
            <div>
                <!--全部折叠|全部展开-->
                
                <div class="layui-btn-group" style="margin-left:15px;">
                    <button class="layui-btn" id="btn-expand"><img src="../images/展开 (3).png"  style="width: 24px;margin-left: 5px;margin-top: -3px;"><span style="margin-left: 3px;">全部展开</span></button>
                    <button class="layui-btn " id="btn-fold">全部折叠<img src="../images/折叠收起.png"  style="width: 24px;margin-left: 5px;margin-top: -3px;"></button>
                </div>
                <span style="padding-left: 100px;">当前菜品ID </span>
                <span style="padding-left: 240px;">菜品名</span>
                <ul style="position:absolute;top:1px; left: 460px;">                
                    <li  style="display: inline-block;"><input  readonly type="text"  name="vid_show" lay-verify="required"   class="layui-input input inp"></li>
                    <li style="margin-left: 70px; display: inline-block;"><input  type="text" name="vname_show"  lay-verify="required" readonly value="666" class="layui-input input inp">                        </li>
                </ul>

                <table id="munu-table" class="layui-table" lay-filter="munu-table"></table>
                
            </div>

            <script type="text/html" id="TPL-treeTable-demo">
                <div class="layui-btn-container">
                    <button class="layui-btn layui-bg-red"  id="delsubbt"><img src="../images/删除 (2).png" lay-event="delSpecs" style="width: 24px;margin-left: -1px;margin-top: -3px;">清空规格</button>
                    <button style="width: 115px;" class="layui-btn lay-submit" id="subbt" lay-event="getChecked"><img src="../images/规格参数.png"  style="width: 24px;margin-left: -1px;margin-top: -3px;">添加规格</button>
                </div>
              </script>  
        </div>

    </div>  
    
    
    <script type="text/html" id="saddprice">
        {{#if (d.isMenu==0) { }}
        <span>无价格可修改...</span>
        {{# }else { }}
         
        <input type="text" {{ d.enable== true ?'':'readonly' }} style="width:120px"  name="{{d.type_speid}}"  lay-verify="required"  lay-reqtext="价格不能为空"   id="myprice" onchange="getprice(this)" value={{d.addprice==null?0:d.addprice}} class="layui-input"/>
        {{# }}}
    </script>


    <!-- <script type="text/html" id="saddprice">
        {{#if (d.mLevel == 1) { }}
        <span>无价格可修改...</span>
        {{# }else if(d.mLevel == 2){ }}
        <input type="text" style="width:120px"  name="{{d.specsid}}"  lay-verify="required"  lay-reqtext="价格不能为空"  id="myprice" onchange="getprice(this)" value={{d.saddprice==undefined?0:d.saddprice}} class="layui-input" {{ d.enable== true&&d.mLevel ==2 ? '' : 'readonly' }} >
        {{# }}}
    </script> -->

    <script type="text/html" id="specs-pic">
        <img id="vpicture" class=".layer-mask" src="{{'../images/'+d.icon}}  " ondblclick="bigimg(this)" style="width:70px;height:50px; title:'点击放大'; cursor: pointer;">
    </script>

    <script type="text/html" id="power-enable">
            <input type="checkbox" id="{{d.type_speid}}"  {{ d.enable== true ? 'checked' : '' }}  name="{{d.isMenu==0?'typeid':'specsid'}}"  value="{{d.isMenu==0?d.type_speid:d.parentId}}"    title='{{d.isMenu==0?"父级":"子级"}}'   lay-skin="switch" lay-text="启用|禁用" lay-filter="user-enable"/>
    </script>  

<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
    <script>
        
        var varid=sessionStorage.getItem("vid");//当前菜品编号
        
        bigimg=function (e){
            layer.photos({
                 photos: { "data": [{"src": e.src}]},
                 shade: [0.7,'#fff']
          });   
        }
        //图片查看 

        layui.config({
            base : '../js/lay-module/'
        }).extend({
            treetable : 'treetable-lay/treetable'
        });

        var SpeUpPrice=[];
        var price;

        function SpecType(varietyId,specTypeId){
        return{"varietyId":varietyId,"specTypeId":specTypeId}; 
        }

        function Specs(varietyId,specId,specAddPrice){
          return{"varietyId":varietyId,"specId":specId,"specAddPrice":specAddPrice};       
        }
        
        
        var requrl="http://localhost:8080/restaurant_web_war_exploded/"   
        
        //用于获取子规格的改动价格和编号
        function getprice (obj){
        if (obj.value===""||obj.value===0){
            layer.msg("价格不允许为空!")
            obj.value=0;
            obj.checked="false";   
            return;
        }else {
            price=obj.value;
            for (let index = 0; index < SpeUpPrice.length; index++) {
                if(SpeUpPrice[index].specId==obj.name){
                    SpeUpPrice.splice(index,1);
                }  
            }//覆盖规格价格
            SpeUpPrice.push(Specs(varid,obj.name,price))
        }
     }//拿修改后的子规格价格和规格便号

        layui.use(['treetable','form','table'], function () {
        var $ = layui.jquery;
        var form=layui.form;
        var table=layui.table;
        var treetable = layui.treetable;
        var hasSpecsType=false;
        var hasSpecs=false;


      //用于格式化数据
       function init(type_speid,type_spename,addprice,isMenu,parentId,enable){
        return {"type_speid":type_speid,"type_spename":type_spename,"addprice":addprice,"isMenu": isMenu,"parentId":parentId,"enable":enable};
        }  
        

    var varSpecs=[];//当前菜品拥有的子规格
    var varSpecsType=[];//当前菜品拥有的父规格

    initVarHasSpecs();  
    function initVarHasSpecs(){
        $.ajax({          
        type:"get",
        url:requrl+"varietySpecs/listVarietySpecs",
        data:{varietyId:varid},
        success:function (res){
            if(res.data!=null){
                hasSpecs=true;
                let list=res.data.list;
                for (let index = 0; index < list.length; index++) {
                //  console.log(list[index]);   
                 varSpecs.push(list[index]);
                 children.push(list[index].specId); 
                 SpeUpPrice.push(Specs(varid,list[index].specId,list[index].specAddPrice));
                } 
            }
        }
      })    
      
      $.ajax({        
        type:"get",
        url:requrl+"varietySpecType/listVarietySpecType",
        data:{varietyId:varid},
        success:function (res){
            if(res.data!=null){
                hasSpecsType=true;
                let list=res.data.list;
                for (let index = 0; index < list.length; index++) {
                // console.log(list[index].specTypeId);   
                varSpecsType.push(list[index])
                parent.push(list[index].specTypeId);      
             } 
          } 
          filterSpces(varSpecs,varSpecsType);  
        }
      }) 
    }
    //初始化已有规格

    function filterSpces(varSpecs,varSpecsType){
        $.ajax({        
        type:"get",
        url:requrl+"varietySpecs/listSpecsType",    
        success:function (res){
           let mytreedata=res.data  
            
            if(varSpecs.length>0){  
            for (let i = 0; i < mytreedata.length; i++) {
                for (const specs of varSpecs) {
                    //如果在全部规格中找到与当前菜品所拥有的规格
                    if(mytreedata[i].type_speid==specs.specId){
                        mytreedata[i].enable=true;
                        mytreedata[i].addprice=specs.specAddPrice;
                    }
                } 
              }
            }   

            if(varSpecsType.length>0){
                for (let i = 0; i < mytreedata.length; i++) {
                for (let j = 0; j < varSpecsType.length; j++) {
                    //如果在全部规格中找到与当前菜品所拥有的父规格
                    if(mytreedata[i].type_speid==varSpecsType[j].specTypeId){
                        mytreedata[i].enable=true;
                    }
                } 
              }
            }
            treerender(mytreedata)
        }
      }) 
    }  
    //过滤规格数据(是否有子规格，价格...)

       // 渲染表格
       // layer.load(2);
    function treerender(datas){
        //      重新渲染数据
        treetable.render({
            treeColIndex: 1,//层级关系展示在第几列
            treeSpid: -1,//是否有最高父id没有-1表示
            treeIdName: 'type_speid',//每条数据id 字段
            treePidName: 'parentId', //每天数据父id字段
            treeDefaultClose: true,
            elem: '#munu-table',//表单id
            data:datas,
            // url:requrl+"varietySpecs/listSpecsType",   
            page: false,
            toolbar: '#TPL-treeTable-demo',
            cols: [[
                {field:"type_spename", width: 265,title: '规格名', align: 'center'},
                {field:'type_speid', width: 265, align: 'center', title: '规格编号'},
                {width: 265,title: '规格价格', templet:'#saddprice', align: 'center'},
                {width: 265,title: '当前规格', templet:'#power-enable', align: 'center'},
                {field: 'isMenu', width: 219, align: 'center', templet: function (d) {
                        if (d.isMenu == 1) {
                            return '<span class="layui-badge layui-bg-gray">子级</span>';
                        }
                        if (d.isMenu == 0) {
                            return '<span class="layui-badge-rim">菜单</span>';                        
                        } 
                    }, title: '类型'
                }
            ]],
            response:{
		      statusName:'errorCode', //规定返回的状态码字段为code
			  statusCode:200 //规定成功的状态码味200
		    }
        });
    }
      //树结构表格渲染 

    //全部展开
     $('#btn-expand').click(function () {
            treetable.expandAll('#munu-table');
        });
     //全部折叠
    $('#btn-fold').click(function () {
            treetable.foldAll('#munu-table');
    });
        

    var ensureDel=false;
    var AddSpecsStatus=false;//是否改动子规格价格
    var parent=[];//修改后父级sid(foodtype)
    var children=[];//修改后子级specsid(specsInfo)
    var specChkId;
    function EnSureSku(data){   
              //选中要添加的规格
            if(data.elem.checked==true){
                let sname= data.elem.name//拿到要操作的规格名(父类:typeid,子类:specsid)
                specChkId=data.elem.id;
                sname==='typeid'?parent.push(data.value):children.push(data.elem.id);
                AddSpecsStatus=true; 
            }else{//选中后又取消添加的规格
                let sname= data.elem.name//拿到要操作的规格名(父类:typeid,子类:specsid)        
                if(sname==='typeid'){
                    for (let index = 0; index < parent.length; index++) {
                      if(parent[index]==data.value){
                        parent.splice(index,1);
                      }
                    }
                }else{
                    var sameids=[];//用于存放改动价格
                    for (let index = 0; index < children.length; index++) {
                      if(children[index]==data.elem.id){                       
                        let samepid=children[index];
                        children.splice(index,1);
                        sameids.push(samepid);
                      }
                    }
                    if(sameids>0){
                        for (let i = 0; i < SpeUpPrice.length; i++) {
                            for (let j = 0; j < sameids.length; j++) {
                                if(SpeUpPrice[i].specId==sameids[j]){
                                    SpeUpPrice.splice(i,1);
                                }   
                            }  
                        }
                    }//移除规格
                }
            } 
        }

    // 添加规格(用于最后做提交)
    table.on("toolbar(munu-table)", function (obj) {
        initVarHasSpecs();
        function DelSameUid(){
            let Sameid;
            for (let i = 0; i < children.length; i++) {
               for (let j = 0; j < i; j++) {
                      if (children[i] === children[j]){
                        children.splice(i,1);
                      }
                   }
               }
            }
            // index= layui.layer.load(3, {  
            // shade: [1,'#fff'] //0.1透明度的白色背景  
            // })
                
            var addvar_specType=[];
            DelSameUid();   
            
            for (let index = 0; index < parent.length; index++) {
               addvar_specType.push(new SpecType(varid,parent[index])); 
            }   

            // console.log("筛选前最终要添加子规格=======");
            // for (let index = 0; index < children.length; index++) {
            //     console.log(children[index]);    
            // }

            
            if(AddSpecsStatus&&hasSpecs){
            let idMap = new Map(SpeUpPrice.map(obj => [obj.specId, true]));//
            let filteredArr = children.filter(item => !idMap.has(item));
                for (let index = 0; index < filteredArr.length; index++) {
                    if(filteredArr[index]!=specChkId){
                        continue;
                    }
                    SpeUpPrice.push(Specs(varid,filteredArr[index],0));//新增菜品规格(为0)
                } 
            }else{
                let idMap = new Map(SpeUpPrice.map(obj => [obj.specId, true]));//
                let filteredArr = children.filter(item => !idMap.has(item));
                for (let index = 0; index < filteredArr.length; index++) {
                    SpeUpPrice.push(Specs(varid,filteredArr[index],0));//新增菜品规格(为0)
                } 
            }


         // console.log("最终要修改的子规格价格=======");
        SpeUpPrice.forEach(function name(params) {
        // console.log("VID: "+params.varietyId+"ID: "+params.specId+" "+"UpPrice: "+params.specAddPrice);
        })
        

        if(obj.event==='getChecked'){    
            AddSpces();
            window.parent.postMessage('addsuccess', 'http://127.0.0.1:5500/index.html#/../html/varietyInfo.html'); // '*' 表示目标源，慎用，建议使用具体的源      
        }else{
         confirmindex= layer.confirm('是否确认清空'+$('input[name="vname_show"]').val()+'的规格?', {icon: 3, title: "系统提示"},function(index){
                if (index === layer.index) { // 或者 index === 'layer-index'，取决于实际值  
                delSpecs();
                delSpecType(); 
                window.parent.postMessage('delsuccess', 'http://127.0.0.1:5500/index.html#/../html/varietyInfo.html'); // '*' 表示目标源，慎用，建议使用具体的源      
                setTimeout(function(){layer.close(confirmindex);},1000)
              } 
          });
        }

        function AddSpces(){
        if(parent.length>0){
            if(hasSpecsType){
                delSpecTypeAdd();
            }else{
                insertSpecType();
            }
        }

        if(children.length>0){//有重新勾选子规格
            if(hasSpecs){//重新勾选前是否有子规格
                delSpecsAdd();
            }else{
                insertSpecs();
            }
          }
        }    

        function insertSpecType(){
            $.ajax({        
                type:"post",
                url:requrl+"varietySpecType/addsVarietySpecType",
                data:JSON.stringify(addvar_specType),
                contentType:'application/json',
                success:function (res){
                    // console.log(res);
                }
            })  
        }   

        function delSpecTypeAdd(){
            $.ajax({        
                type:"post",
                url:requrl+"varietySpecType/deletesVarietySpecType",
                traditional:true,
                data:{varietyId:[varid],specTypeId:parent},
                success:function (res){
                    if(res.errorCode==200){
                        insertSpecType();
                    }
                  }
            }) 
        }    

        function delSpecType(){
            $.ajax({        
                type:"post",
                url:requrl+"varietySpecType/deletesVarietySpecType",
                traditional:true,
                data:{varietyId:[varid],specTypeId:parent},
                success:function (res){
                        // console.log(res);
                  }
            }) 
        }     

        function insertSpecs(){
            let code;
                $.ajax({        
                type:"post",
                url:requrl+"varietySpecs/addsVarietySpecs",
                contentType:'application/json',
                data:JSON.stringify(SpeUpPrice),
                success:function (res){
                }
            }) 
        }

        function delSpecsAdd(){
            $.ajax({        
                type:"post",
                url:requrl+"varietySpecs/deletesVarietySpecs",
                traditional:true,
                async:true,
                data:{varietyId:[varid],specId:children},
                success:function (res){
                    if(res.errorCode==200){
                          insertSpecs();  
                    }
                }
            }) 
        }   

        function delSpecs(){
            $.ajax({        
                type:"post",
                url:requrl+"varietySpecs/deletesVarietySpecs",
                traditional:true,
                async:true,
                data:{varietyId:[varid],specId:children},
                success:function (res){
                    // console.log(res);
                }
            }) 
        }    
        
    });     

    // 监听 checkbox 的点击事件  
    form.on('switch(user-enable)', function(data){  

                var checked = this.checked; // 当前 checkbox 的状态  
                var tr = $(this).closest('tr'); // 当前行的 tr 元素  
                let input=$(tr).find("td:eq(2) div input")//拿到文本框  

                input.prop("readonly",!data.elem.checked)//通过规格状态来对文本框进行控制
                var currentAuthorityId=data.elem.value;//当前规格编号
                var level = data.elem.title; // 获取当前行的层级（假设你在渲染时设置了该属性）  

                // 更新子级 checkbox 的状态（如果当前是父级）  
                if (level === '父级') { // 假设层级为 0 或未定义的是父级  
                    // 遍历所有子级，并更新它们的 checkbox 状态  
                    // 你需要根据你的数据结构和 DOM 结构来编写这部分逻辑  
                    // 示例代码假设所有子级的 checkbox 都包含在当前行的子元素中  
                        var typeid = data.elem.value; //拿到父级编号
                        tr.nextAll().each(function() {  //遍历所有行
                        var subTr = $(this);     
                        var checkbox=subTr.find('input[type="checkbox"]')

                        var input=subTr.find('input[type="text"]')
                        let speid= $(checkbox).val();
                        let mytitle=$(checkbox).prop("title")
                        let filterid;       

                        //如果通过父级编号找到子级    
                        if(typeid===speid && mytitle==='子级'){ 
                            checkbox.prop('checked', checked);  //联动上子级(对子级进行勾选)
                            input.prop("readonly",false); //启用文本框
                           
                           if($(checkbox).prop("checked")){
                            filterid= $(checkbox).prop("id");
                            children.push(filterid);//添加到 children[]    
                           }else if(!$(checkbox).prop("checked")){
                            input.prop("readonly",true);//禁用文本框
                            children=children.filter(item => item==filterid&&item==data.elem.id);//过滤掉以及删除而后取消选中后的规格
                           }
                        }
                    });  
                }

                var dadCheckbox;//父级节点
                // 检查所有子级节点是否全部选中的函数  
                function areAllChildrenChecked(parentId) { 
                    var allChecked = true; // 假设所有子级节点默认都是选中的 
                    var  dadid;
                    var mylength=$('div[lay-id="munu-table"] div.layui-table-box div.layui-table-body table tbody tr').each(function() {  
                        var subTr = $(this);  
                        var checkboxs = subTr.find('input[type="checkbox"]');  
                        let speid= $(checkboxs).val();   
                        let title= $(checkboxs).prop("title");
                        
                        //如果父级节点
                        if(speid===parentId&&title==='父级'){
                            //获取父级节点
                            dadCheckbox = subTr.find('input[type="checkbox"]');
                        }

                        // 检查当前遍历行的 parentId 是否与父级节点的 authorityId 相匹配  
                        if (speid === parentId&&title==='子级') {
                            var childrenchk = subTr.find('input[type="checkbox"]');  
                            // 如果有任何一个子级节点的 checkbox 未被选中，则将 allChecked 设置为 false  

                           if(!$(dadCheckbox).is(":checked")){
                            if (!childrenchk.is(':checked')) {
                                    //子级有一个不选中父级就不变
                                allChecked = false;   
                                return false; // 跳出 each 循环 
                            }
                           }

                            if(childrenchk.is(":checked")&&!$(dadCheckbox).is(":checked")){
                                dadid=$(dadCheckbox).val()
                                allChecked=true;
                            }    
                        }  
                    });     
                if(dadid!=undefined){
                    parent.push(dadid);  
                }    
                return allChecked;  
                }  

                EnSureSku(data);//筛选父子级规格数据

                // 根据子级节点的选中状态更新父级节点的 checkbox  
                if (areAllChildrenChecked(currentAuthorityId)) {  
                $(dadCheckbox).prop('checked', true); 
                }   
                else{
                $(dadCheckbox).prop('checked', false); 
                dadid=0; 
                parent=parent.filter(item=> item==$(dadCheckbox).prop("id"))} 
                        
                // 重新渲染 form，以确保 checkbox 的样式正确显示  
                form.render('checkbox');  
             });  
             
});
    </script>    
</body>
</html>